package com.sc.ifs.goods;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sc.dal.common.pagination.PaginationBean;
import com.sc.dal.mapper.goods.GoodsMapper;
import com.sc.dal.model.consultComment.ConsultComment;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.Sku;
import com.sc.dal.model.goods.SkuValue;
import com.sc.service.consultComment.ConsultCommentService;
import com.sc.service.goods.GoodsService;
import com.sc.service.promotion.PromotionService;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DataUtil;
import com.sc.util.exception.ExceptionEnum;
import com.sc.util.exception.ScBizException;

/**
 * 商品管理
 * @author maoyongbin
 * @edit xiongyong 2017.3.17
 * @日期 Mar 15, 2017 9:59:34 AM
 */
@Controller
@RequestMapping(value="app/goods")
public class GoodsController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private PromotionService promotionService;
	@Autowired
	private ConsultCommentService consultCommentService;
	/**
	 * 根据条件查找商品列表数据
	 * @param request
	 * @param currPage
	 * @param pageSize
	 * @return Map<String, Object>
	 */
	@RequestMapping(value="selectList",method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> selectList(HttpServletRequest request,Integer currPage, Integer pageSize){
		Map<String,Object> resultMap = new LinkedHashMap<String,Object>();
		
		List<Map<String, Object>> resultList = null;
		int totalRecords = 0;	//总记录数
		int totalPage = 0;		//总页数
		//设置查询参数
		Map<String,Object> paramMap = new HashMap<String,Object>();
		//获取数据
		String searchValue = request.getParameter("searchValue");	//搜索内容
		String classCode = request.getParameter("classCode");	//商品分类编码
		String classId = request.getParameter("classId");  //商品分类ID
		String type = request.getParameter("type");	//商品类型
		String sort = request.getParameter("sort");	//商品类型
				
		if(StringUtils.isNotBlank(searchValue)){	
			paramMap.put("name", searchValue);
		}
		if(StringUtils.isNotBlank(classCode)){
			paramMap.put("classCode", classCode);
		}
		if(StringUtils.isNotBlank(classId)){
			paramMap.put("classId", classId);
		}
		if(StringUtils.isNotBlank(type)){
			paramMap.put("type", type);
		}
		if(StringUtils.isNotBlank(sort)){
			paramMap.put("sort", sort);
		}
		
		try{
			//查询商品数据
			PaginationBean<Map<String,Object>> pagination = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "count","selectList",GoodsMapper.class);
			resultList = pagination.getPageList();//返回数据
			for(Object o :resultList){
				Goods goods  =  (Goods) o;
				String imageFile = goods.getImageFile();
				String imageFile_new ="";
				if(Common.isNotEmpty(imageFile)){
					String[] imageFiles = imageFile.split(";");	
					if(imageFiles != null ){
						for(String im: imageFiles){
							imageFile_new += ConfigBeanAdapter.fileAccessAddress + im+";";							
						}
					}
				}
				goods.setImageFile(imageFile_new);	
				if(Common.isNotEmpty(goods.getPicture())){
					goods.setPicture(ConfigBeanAdapter.fileAccessAddress + goods.getPicture());
				}
				Integer goodsId = goods.getId();
				String goodsType = goods.getType();
				if(goodsId!=null){
					/***获取该商品的月销量****************/
					int monthSaleMount =  goodsService.selectGoodsMonthSaleMount(goodsId);	
					goods.setMonthSaleMount(String.valueOf(monthSaleMount));
					/***商品折扣信息***********/
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("goodsId", goodsId);
					String proTitle="";
					if(goodsType!=null){
						String goodstypeTemp[] = goodsType.split("-");
						for (int i = 0; i < goodstypeTemp.length; i++) {
							if("09".equals(goodstypeTemp[i])){
								proTitle="包邮、";
							}
						}
					}
					proTitle += promotionService.getGoodsByPromtion(map);
					if(proTitle.endsWith("、")){
						proTitle = proTitle.substring(0, proTitle.length()-1);
					}
					goods.setProTitle(proTitle);
				}
			}
			totalRecords = pagination.getTotalRecords();//返回行数
			totalPage = pagination.getTotalPage();
			
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS, totalRecords, totalPage, resultList);
			logger.info("查询商品数据成功!");
		}catch(Exception e){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询商品数据异常:"+e);
			throw new ScBizException("查询商品数据异常！", e);
		}
		
		return resultMap;
	}
	
	/***
	 * 根据id查看商品详细信息
	 * @param id 2
	 * mId 111111
	 * @return  mId
	 */
	@RequestMapping(value="selectOne")
	@ResponseBody
	public Map<String, Object> selectOne(HttpServletRequest request,Integer id,String  mId){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		if(id==null ){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
			logger.warn("查询参数为null！");
		}else {
			try{
				Goods goods = this.goodsService.selectByPrimaryKey(id,mId);
				if(goods!=null){
					List<Sku> skuList = goods.getGoodsSkuList();
					if(skuList!=null && skuList.size()>0){
						for (int i = 0; i < skuList.size(); i++) {
							Sku sku = skuList.get(i);
							List<SkuValue> goodValue = sku.getGoodsSkuValueList();
							if(goodValue.size()<=0){
								goods.setGoodsSkuList(null);
							}
						}
					}
					/***获取该商品的月销量****************/
					int monthSaleMount =  goodsService.selectGoodsMonthSaleMount(id);	
					goods.setMonthSaleMount(String.valueOf(monthSaleMount));
					/**统计商品评价数、交易成功数****/
					List<Integer> totalCount = goodsService.statisticsGoodsDetails(id);
					/**获取一条商品评价信息********/
					Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
					paramMap.put("goodsId", id);
					paramMap.put("type", Constants.TYPE_B);
					paramMap.put("status", "0");
					List<ConsultComment> commentList = consultCommentService.queryMessageList(paramMap);
					
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS, goods);
					/*****商品描述url地址*********/
					resultMap.put("goodsDepictUrl", ConfigBeanAdapter.siteUrl+"/pages/goodsDepict.jsp?goodsId="+id);
					/*****商品参数url地址*********/
					resultMap.put("goodsParamUrl", ConfigBeanAdapter.siteUrl+"/pages/goodsParam.jsp?goodsId="+id);
					if(commentList!=null && commentList.size()>0){
						resultMap.put("consultComment", commentList.get(0));
					}else{
						resultMap.put("consultComment", null);
					}
					resultMap.put("evaluateCount", totalCount.get(0));
					logger.warn("查询商品详情成功！");
				}else{
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
					logger.warn("查询商品详情失败！");
				}
			}catch(Exception e){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
				logger.error("查询商品数据异常"+e);
				throw new ScBizException("查询商品数据异常！", e);
			}
		}
		return resultMap;
	}
	/**
	 * 查找推荐商品
	 * @return Map<String, Object>
	 */
	@RequestMapping(value="selectListRecommend", method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> selectListRecommend(){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		
		try{
			List<Goods> goodsList = this.goodsService.selectListRecommend();
			if(goodsList!=null && goodsList.size()>0){
				//处理商品数据
				List<Map<String, Object>> resultMapList = handleGoodsData(goodsList);
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS, resultMapList);
				logger.warn("查询商品详情成功！");
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
				logger.warn("查询商品详情失败！");
			}
		}catch(Exception e){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询商品数据异常"+e);
			throw new ScBizException("查询商品数据异常！", e);
		}
		
		return resultMap;
	}
	
	/**
	 * 处理商品数据(树型结构)
	 * @param goodsList
	 */
	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> handleGoodsData(List<Goods> goodsList){
		List<Map<String, Object>> resultListMap = new ArrayList<Map<String, Object>>();
		Map<String, Object> tempMap = new LinkedHashMap<String, Object>();	//临时的map数据，用来判断是否已经存此分类 
		for(Goods goods : goodsList){
			if(tempMap.get(goods.getClassId())==null){
				List<Goods> resultList = new ArrayList<Goods>();	//商品集合list
				Map<String, Object> classMap = new LinkedHashMap<String, Object>();	//创建分类map
				
				resultList.add(goods);
				
				classMap.put("classId", goods.getClassId());	//分类id
				classMap.put("className", goods.getClassName());//分类名称
				classMap.put("classIcon", goods.getIcon());	//分类图标
				classMap.put("goods", resultList);	//把商品集合list放到分类map中
				
				tempMap.put(goods.getClassId(), classMap);	//把分类map放到临时map中
				
				resultListMap.add(classMap);	//把
			}else{
				Map<String, Object> classMap = (Map<String, Object>)tempMap.get(goods.getClassId());	//从临时map中获取已经存放的分类map
				((List<Goods>)classMap.get("goods")).add(goods);//从分类map中获取已经存在的商品集合list，并把商品数据重新放到商品集合list中
			}
		}
		
		return resultListMap;
	}
	
	
}
